package com.lsk.api;

import com.jfinal.json.Json;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.util.UrlEncoded;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.*;

/**
 * 闲卡网
 */
public class XKService {

    public static String dev_id = "100006338111";//接口id

    public static String dev_token = "e616d903fac9df367752b4edc43a36df";

    public static String cardSubmitUrl = "http://api.xiankawang.com/league/procreate";

    public static String cardListUrl = "http://api.xiankawang.com/league/product";


    public static String phone = "13336670850";


    static Cache cache = Redis.use();

    public static void cardSubmit(Record temp) {

        String cacheCardId = temp.getStr("id");

        String xkId = Db.queryStr("select xkId from commodity where id =?", temp.getStr("commodityId"));

        /*查询商品对应的闲卡网卡片信息*/

        Record myData = new Record();

        String sql = "SELECT *from xy_commodity where commodityId='" + xkId + "'";

        Record xkRecord = Db.findFirst(sql);
        /** 查找commodity_facevalue 中xkCommodityId ,查找 下列三个参数    */
        String xkCommodityDetailId = Db.queryStr("select xkCommodityId from commodity_facevalue where id =(select feedbackId from card where id =?)", cacheCardId);
        Record xkCommodity = Db.findFirst("select * from xy_commodity where commodityDetailId =?", xkCommodityDetailId);

        if (xkCommodity != null) {

            Map<String, Object> parameters = new HashMap<>();

            parameters.put("dev_id", dev_id);

            parameters.put("dev_token", dev_token);


            parameters.put("product_detail_id", xkCommodity.getStr("commodityDetailId"));

            parameters.put("product_type_id", xkCommodity.getStr("commodityTypeId"));

            parameters.put("product_id", xkCommodity.getStr("commodityId"));

            String orderId = "XK" + DateUtil.getSdfTimes() + Tools.getRandomNum();

            parameters.put("third_order_sn", orderId);

            List cards = new ArrayList<>();

            List card = new ArrayList();

            card.add(encryption(temp.getStr("cardNumber")));

            card.add(encryption(temp.getStr("cardPassword")));

            cards.add(card);

            parameters.put("cards", cards);

            String result = HttpClientPostByJson(cardSubmitUrl, JsonUtil.getJsonStr(parameters));

            System.out.println(result);


            if (result.contains("data")) {//提交成功

                myData.set("returnCode", 4).set("returnMsg", "提交成功(闲卡网)");

                Db.update("update card set state = 2 ,msg=? where id =?","已推送到闲卡网",cacheCardId);

            } else {

                Map<String, Object> resultMap = JsonUtil.getMapFromJsonObjStr(result);

                Syslog.info(resultMap);

                myData.set("returnCode", 4).set("returnMsg", resultMap.get("message"));
                //推送失败
                Db.update("update card set state = 3 ,msg=? where id =?",resultMap.get("message"),cacheCardId);
            }

            String cardId = temp.getStr("id");

            temp.remove("code").set("createTime", new Date()).set("returnJson", result)
                    .remove("id").set("cardId", cardId).set("sendOrderId", orderId).remove("msg").remove("payState");

            myData.set("id", orderId).set("cardId", cardId).set("classId", temp.getStr("classId")
            ).set("commodityId", temp.getStr("commodityId")).set("commodityName", temp.getStr("commodityName"))
                    .set("feedbackId", temp.getStr("feedbackId")).set("feedbackValue", temp.getStr("feedbackValue"))
                    .set("discount", temp.getStr("discount")).set("createTime", new Date())
                    .set("returnJson", result).set("cardNumber", temp.getStr("cardNumber")).set("cardPassword", temp.getStr("cardPassword"))
                    .set("orderId", temp.getStr("orderId")).set("memberId", temp.getStr("memberId")).set("imgPath", temp.getStr("imgPath"))
                    .set("className", temp.getStr("className"));
            Db.save("card_send_logs", "id", myData);

            //Db.save("card_send_logs", "id", temp);

            Syslog.info("向闲卡平台推送成功");

            Syslog.info("推送闲卡平台结束，返回结果为：" + result);

            cache.setex("card_send_logs" + cacheCardId, 60 * 30, myData);

        } else {

            Syslog.info("未配置闲卡网对应信息");

            Db.update("update card set state =1 ,msg = ? where id =?", "未关联闲卡网商品", cacheCardId);

            myData.set("returnMsg", "未配置闲卡网对应信息");

            cache.setex("card_send_logs" + cacheCardId, 60 * 30, myData);

        }


    }

    /**
     * 卡列表
     */
    public static void getCards() {

        Map<String, String> parameters = new HashMap<>();

        parameters.put("dev_id", dev_id);

        parameters.put("dev_token", dev_token);

        System.out.println(JsonUtil.getJsonStr(parameters));

        String result = HttpKit.post(cardListUrl, parameters, "");

        Map<String, Object> resultMap = JsonUtil.getMapFromJsonObjStr(result);

        System.out.println(result);

        List<JSONObject> dataList = (List<JSONObject>) resultMap.get("data");//接口中的data数组
        List<Record> myList = new ArrayList<>();        //结果
        for (JSONObject r : dataList) {
            if (r == null) {
                continue;
            }
            String commodityTypeName = r.get("name").toString();//卡类型名称
            JSONArray array = r.getJSONArray("products");       //所有的卡
            for (int i = 0; i < array.size(); i++) {
                if (array.getJSONObject(i) == null) {
                    continue;
                }
                String commodityName = array.getJSONObject(i).get("name").toString();   //卡名称
                JSONArray details = array.getJSONObject(i).getJSONArray("product_details");//所有的卡面值
                for (int j = 0; j < details.size(); j++) {
                    JSONObject detail = details.getJSONObject(j);
                    String commodityId = detail.get("product_id").toString();       //卡id
                    String commodityType = detail.get("product_type_id").toString();    //卡类型id
                    String recycleDiscount = detail.get("recycle_discount").toString(); //卡的折扣
                    String fieldType = detail.get("field_type").toString();
                    String commodityDetailId = detail.get("id").toString();
                    Record re = new Record().set("commodityId", commodityId).set("id", UuidUtil.get32UUID())
                            .set("commodityTypeId", commodityType).set("commodityName", commodityName)
                            .set("commodityTypeName", commodityTypeName).set("recycleDiscount", recycleDiscount)
                            .set("fieldType", fieldType).set("commodityDetailId", commodityDetailId);
                    myList.add(re);
                }

            }

        }
        for (Record record : myList) {
            /**
             * 判断数据库中是否存在 要存的面值信息
             */
            int count = 0;
            count = Db.queryInt("select count(*) from xy_commodity where commodityDetailId='" + record.get("commodityDetailId") + "'"
                    + "and  commodityId ='" + record.get("commodityId") + "'"
            );
            if (count == 0) {
                Db.save("xy_commodity", record);
            }
        }

    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encryption(String data) {

        String iv = phone.substring(3);

        iv = MD5.md5(iv);

        iv = iv.substring(8, 24);

        String key = MD5.md5(dev_token).substring(8, 24);


        String result = AES.AESEncodeIvKey(data, iv, key);

        System.out.println(result);

        return result;

    }


    /**
     * @param strings
     */

    public static void main(String[] strings) {


    }


    /**
     * post请求
     */
    public static String HttpClientPostByJson(String url, String param) {

        String result = "";
        try {
            //创建client和post对象
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            //json形式
            post.addHeader("content-type", "application/json;charset=utf-8");
            post.addHeader("accept", "application/json");
            //json字符串以实体的实行放到post中
            post.setEntity(new StringEntity(param, Charset.forName("utf-8")));
            HttpResponse response = null;
            try {
                //获得response对象
                response = client.execute(post);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                post.releaseConnection();
            }

            if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                System.out.println("请求返回不正确");
            }


            try {
                //获得字符串形式的结果
                result = EntityUtils.toString(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }


            System.out.println(result);


        }catch (Exception e){

            Syslog.error("闲卡网推送异常");
            Syslog.error(e);

        }
        return result;
    }


}
